/* 
 * File:   IPC_mmap.cpp
 * Author: kisme
 * 
 * Created on May 11, 2011, 3:45 PM
 */

#include "MMAP_IO.h"

//
// struct part
//
template<class NodeT>
Mmap_IO_Conf<NodeT>::Mmap_IO_Conf()
{
    this->m_nFileFd = 0;
}



//
// class part
//

template<class NodeT>
MMAP_IO<NodeT>::MMAP_IO()
{
    mmap_io_conf = new Mmap_IO_Conf<NodeT>();
}

template<class NodeT>
MMAP_IO<NodeT>::MMAP_IO(const MMAP_IO& orig)
{
    mmap_io_conf = new Mmap_IO_Conf<NodeT>();
}

template<class NodeT>
MMAP_IO<NodeT>::~MMAP_IO()
{
    mmap_io_conf = new Mmap_IO_Conf<NodeT>();
}

template<class NodeT>
int MMAP_IO<NodeT>::initFd(char* filePath)
{
    fprintf(stdout, "fd begin...\n");
    int status = 0;
    this->mmap_io_conf->m_nFileFd = open(filePath, O_CREAT | O_RDWR | O_TRUNC);
    fprintf(stdout, "fd finish..\n");
    if (this->mmap_io_conf->m_nFileFd) {
        status = 0;
    }
    else {
        status = -1;
    }
    return status;
}

template<class NodeT>
int MMAP_IO<NodeT>::initSpace(int nodelen)
{
    printf("len: %d \n", sizeof (NodeT) * nodelen);
    this->mmap_io_conf->m_nNodeLen = nodelen;
    this->mmap_io_conf->m_nMenLen = sizeof (NodeT) * nodelen;
    lseek(this->mmap_io_conf->m_nFileFd, this->mmap_io_conf->m_nMenLen, SEEK_SET);  
//    write(this->mmap_io_conf->m_nFileFd, "", 1);
    return 0;
}

template<class NodeT>
int MMAP_IO<NodeT>::initPtr(int offset)
{
    int status = 0;
    if (this->mmap_io_conf->m_nFileFd) {
        this->mmap_io_conf->m_pPtr = (NodeT*) mmap(NULL, this->mmap_io_conf->m_nMenLen, PROT_READ | PROT_WRITE,
                                  MAP_SHARED, this->mmap_io_conf->m_nFileFd, offset);
        if (this->mmap_io_conf->m_pPtr) {
            // ptr init success.
            status = 0;
        }
        else {
            // ptr init failed.
            status = 1;
        }
    }
    else {
        // fd hasn't bean init.
        status = 2;
    }
    // close file
    close(this->mmap_io_conf->m_nFileFd);
    
    return status;
}

template<class NodeT>
int MMAP_IO<NodeT>::closeFd()
{
    int status = 0;
    if (this->fd) {
        close(this->fd);
        status = 0;
    }
    else {
        status = 1;
    }
    return status;
}

template<class NodeT>
int MMAP_IO<NodeT>::memwrite(NodeT* struct_content)
{
    this->mmap_io_conf->m_pPtr = struct_content;
    return 0;
}

template<class NodeT>
int MMAP_IO<NodeT>::memread(NodeT* struct_content)
{
    struct_content = this->mmap_io_conf->m_pPtr;
    return 0;
}

template<class NodeT>
int MMAP_IO<NodeT>::memsync()
{
    return msync(this->mmap_io_conf->m_pPtr, this->mmap_io_conf->m_nMenLen, MS_SYNC);
}

template<class NodeT>
int MMAP_IO<NodeT>::menunmap()
{
    return munmap(this->mmap_io_conf->m_pPtr, this->mmap_io_conf->m_nMenLen);
}

template<class NodeT>
int MMAP_IO<NodeT>::getMenorySize()
{
    return this->mmap_io_conf->m_nMenLen;
}

template<class NodeT>
int MMAP_IO<NodeT>::getNodeNum()
{
    return this->mmap_io_conf->m_nNodeLen;
}







